package com.netnovelstore.interceptor;

import com.netnovelstore.config.JwtUtil;
import com.netnovelstore.pojo.User;
import com.netnovelstore.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AdminInterceptor implements HandlerInterceptor {

    private RedisUtil redisUtil;

    @Autowired
    public AdminInterceptor(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // http 的 header 中获得token
        String token = request.getHeader("authorization");
        log.info("[AdminInterceptor] token : " + token);

        // token 不存在
        if (token == null || token.equals("")) {
            log.error("AdminInterceptor class token is not exist");
            response.sendError(401,"拒绝访问 : 无身份");
            return false;
        }
        //管理员用
        if (token.equals(JwtUtil.secret))
            return true;
        // 验证 token
        String sub = JwtUtil.validateToken(token);
        if (sub == null || sub.equals("")) {
            log.warn("token exist, but not same");
            response.sendError(403,"拒绝访问 : 身份错误");
            return false;
        }


        User user = (User) redisUtil.get(token);
        if(user == null) {
            log.warn("[AdminInterceptor] has not this user");
            response.sendError(403,"拒绝访问 : 身份错误");
            return false;
        }
        if("admin".equals(user.getUserType())){
            log.info("[AdminInterceptor] user_type : admin");
            return true;
        }
        log.warn("[AdminInterceptor] user_type : user");
        response.sendError(403,"拒绝访问 : 身份错误");
        return false;
    }

}
